<template>
  <div class="app-container">
    <el-row>
      <el-col class="flex">
        <el-cascader
          v-model="queryParams.deptId"
          :options="deptOptions"
          :props="{ value: 'deptId', label: 'deptName', checkStrictly: true, emitPath: false }"
          placeholder="选择站办所"
          @change="handleDeptChange"
          ref="CascaderRef"
        ></el-cascader>
        <el-select v-model="queryParams.year" placeholder="选择年份" class="ml-10" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="选择季度" class="ml-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="text-banner">
      <p>
        <span>服务效能评价</span>
        <span style="margin-left: 30px; font-size: 16px; font-weight: normal">
          <i class="el-icon-warning"></i>
          随机抽查，出现一例“不满意”扣{{ deductionScore }}分
        </span>
      </p>
      <div>
        <span style="font-weight: normal; font-size: 16px"
          >总扣分 <b style="color: #e64242; padding: 0 10px">{{ deductionTotalScore }}</b
          >分</span
        >
        <el-button class="ml-10" size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
      </div>
    </div>

    <div style="display: flex; align-items: center; justify-content: space-between">
      <div class="el-upload__tip" style="margin-top: 0">
        <p>
          <b style="color: #f56c6c">*录音材料：</b>大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> 格式为
          <b style="color: #f56c6c">{{ fileType.join('/') }}</b
          >的文件（不超过<b style="color: #f56c6c">{{ limit }}</b
          >项）
        </p>
      </div>
      <div class="align-right">
        <el-button
          icon="el-icon-s-claim"
          size="mini"
          type="primary"
          plain
          @click="handleSubmit"
          v-hasPermi="['evaluation-comment:performance:submit']"
          >保存并提交</el-button
        >
      </div>
    </div>

    <div class="table">
      <el-table :data="workList" ref="table" border height="100%" v-loading="loading">
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="worker" label="评分对象" width="180" align="center">
          <template slot-scope="scope">
            <el-input v-model.trim="scope.row.worker" placeholder="输入评分对象"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="140" align="center">
          <template slot-scope="scope">
            <el-input v-model.trim.number="scope.row.phone" placeholder="输入联系电话" type="tel" minlength="11" maxlength="11"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="responsibilityDict" label="职能职责" width="150" align="center">
          <template slot-scope>
            <dict-tag :options="dict.type.biz_dept_responsibility_dict" :value="responsibilityDict"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column v-for="item in dict.type.biz_evaluate_grade" :key="item.value" :label="item.label" width="120" align="center">
          <template slot-scope="scope">
            <el-radio v-model="scope.row.evaluateGradeDict" :label="item.value">{{ item.label }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remarks" type="textarea" :rows="1" :autosize="{ minRows: 1, maxRows: 3 }" placeholder="输入备注"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="voiceMaterialUrls" label="音频材料" min-width="180" align="center">
          <template slot-scope="scope">
            <FileUpload v-model="scope.row.voiceMaterialUrls" :isShowTip="false" :fileType="fileType"></FileUpload>
          </template>
        </el-table-column>
        <el-table-column label="扣分" width="150" align="center">
          <template slot-scope="scope">
            <span>{{ rowScoreCompute(scope.row.evaluateGradeDict) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { list, edit } from '@/api/work-approval/evaluation-comment/performance'
import { deptTreeSelectV2 as deptTreeSelect } from '@/api/system/user'
import { quarterFormat } from '@/utils/quarter.js'
import { getDicts } from '@/api/system/dict/data.js'
import FilePreview from '@/components/FilePreview'
import FileUpload from '@/components/FileUpload'
import { mixins } from '@/mixins'
export default {
  name: 'evaluation-comment_performance',
  dicts: ['biz_work_year_list', 'biz_evaluate_service_type', 'biz_evaluate_grade', 'biz_dept_responsibility_dict'],
  props: {},
  mixins: [mixins],
  components: { FilePreview, FileUpload },
  data() {
    return {
      fileType: ['mp3', 'm4a', 'ogg'],
      responsibilityDict: null,
      workMaxScore: 0, // 绩效办评价评议分数
      // 站办所树选项
      deptOptions: [],
      loading: false,
      quarterOptions: [],
      workList: [],
      workItem: {
        id: '',
        worker: '',
        phone: '',
        // serviceTypeDict: '',
        evaluateGradeDict: '',
        remarks: ''
      },
      workMapping: {
        worker: '评分对象',
        phone: '联系电话',
        // serviceTypeDict: '服务类型',
        evaluateGradeDict: '评价等级'
      },
      queryParams: {
        deptId: '',
        year: '',
        quarter: ''
      }
    }
  },
  computed: {
    // 总扣除分数
    deductionTotalScore() {
      let count = 0
      for (let item of this.workList) {
        if (item.evaluateGradeDict === 'BMY') {
          count += 1
        }
      }
      if (count / 30 > 0.6) {
        return this.workMaxScore * -1
      } else {
        let totalScore = this.workList.reduce((prev, curr) => {
          let score = 0
          if (curr.evaluateGradeDict === 'BMY') score = this.deductionScore
          return prev + score
        }, 0)
        totalScore *= -1
        if (Number.isInteger(totalScore)) {
          return totalScore
        } else {
          return totalScore.toFixed(2)
        }
      }
    },
    // 每项指标扣除分数
    deductionScore() {
      let score = this.workMaxScore / 120
      return this.numberParse(score, 2)
    }
  },
  watch: {
    // 监听 $route 对象的变化
    '$route': {
      immediate: true,
      handler(to, from) {
        let { query } = to
        if (query) {
          this.queryParams = { ...query }

          if (query.deptId) {
            this.queryParams = Number(query.deptId)
          }
          this.getList()
        }
      }
    }
  },
  created() {
    this.getWorkScore()
    this.getDeptTree()
  },

  methods: {
    // 获取工作分数限制
    getWorkScore() {
      getDicts('biz_dept_norm_config').then(res => {
        let { data } = res
        this.workMaxScore = data.find(item => item.dictValue === 'JXB_PJPY')?.remark
      })
    },
    // 保存并提交评价评议
    handleSubmit() {
      let workMapping = Object.keys(this.workMapping)
      let index = 0
      const phonePattern = /^1[3456789]\d{9}$/
      for (let item of this.workList) {
        let rowPassCount = 0
        index += 1
        for (let key of workMapping) {
          if (item[key] || item[key] === 0) {
            if (key === 'phone') {
              let isPhone = phonePattern.test(item[key])
              if (!isPhone) {
                this.$modal.msgError(`第 【${index}】 行手机号格式不正确，请检查修改后提交！`)
                return
              }
            }
            rowPassCount += 1
          }
        }
        if (rowPassCount !== 0 && rowPassCount !== workMapping.length) {
          this.$modal.msgError(`第 【${index}】 行存在未填写数据，请填写完整后提交！`)
          return
        }
      }
      let params = { ...this.queryParams, evaluateRecordsList: this.workList }
      edit(params).then(res => {
        this.$modal.msgSuccess('已提交')
        this.handleRefresh()
      })
    },
    // 选择站办所
    handleDeptChange(raw) {
      this.handleRefresh()
      this.$refs.CascaderRef.dropDownVisible = false
    },
    // 刷新
    handleRefresh() {
      let options = this.deptOptions
      let result = findDeptInfo(options, this.queryParams.deptId)
      this.responsibilityDict = result ? result.responsibilityDict : null
      function findDeptInfo(options, deptId) {
        let result = null
        for (let item of options) {
          if (item.deptId === deptId) {
            result = item
            break
          } else {
            if (Array.isArray(item.children) && item.children.length) {
              result = findDeptInfo(item.children, deptId)
              if (result) break
            }
          }
        }
        return result
      }
      this.getList()
    },

    /** 查询站办所下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = this.removeEmptyChildren(response.data[0].children)
        this.queryParams.deptId = this.deptOptions[0].deptId
        this.handleYearChange(new Date().getFullYear())
      })
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      this.handleRefresh()
    },
    // 表格行分数计算
    rowScoreCompute(dict) {
      if (dict === 'BMY') {
        return this.deductionScore * -1
      }
      return 0
    },
    getList() {
      this.loading = true
      list(this.queryParams)
        .then(res => {
          this.loading = false
          this.workList = res.rows
          if (this.workList.length < 30) {
            let list = []
            for (let i = 0; i < 30 - this.workList.length; i++) {
              list.push(JSON.parse(JSON.stringify(this.workItem)))
            }
            this.workList = this.workList.concat(list)
            this.$refs.table.doLayout()
          }
        })
        .catch(err => (this.loading = false))
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .table {
    flex: 1;
    overflow-y: hidden;
  }
}
</style>
